package com.mysite.springbootdemo.controller;

import com.mysite.springbootdemo.po.AcOperator;
import com.mysite.springbootdemo.service.OperatorService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.*;

@Controller
public class LoginController {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private OperatorService operatorService;

	@Autowired
	private RedisTemplate<String, Object> redisTemplate;

	@RequestMapping("/")
	public ModelAndView index(HttpSession session) {
		ModelAndView mv = new ModelAndView("index");
		ModelMap modelMap = mv.getModelMap();
		String name = Math.random() + "";
		modelMap.put("username", name);
		logger.info(name);

		this.redisTemplate.opsForValue().set("username", name);

		AcOperator operator = new AcOperator();
		operator.setUsername(name);
		System.err.println("***************************" + operator);
		this.redisTemplate.opsForValue().set("operator", operator);

		System.err.println(session);
		session.setAttribute("name", name);

		return mv;
	}

	@RequestMapping("/register")
	@ResponseBody
	public String register(HttpSession session) {
		String username = Math.random() + "";
		return operatorService.register(username);
	}

	@RequestMapping("/data")
	@ResponseBody
	public List<AcOperator> data(HttpSession session) {

		System.err.println("*************************** : " + this.redisTemplate.opsForValue().get("username"));

		AcOperator operator = (AcOperator) this.redisTemplate.opsForValue().get("operator");
		System.err.println("*************************** : " + operator + " >> " +operator.getUsername());

		System.err.println("******************** name in session : " + session.getAttribute("name"));

		return operatorService.getOperators(null);
	}
}
